package com.defangit.award.extend.wxmp.config;

import com.defangit.award.domain.WinningInfo;
import com.defangit.award.orm.AwardService;
import com.defangit.award.orm.WinningInfoService;
import com.defangit.openapis.wechat.mp.message.resp.ResponseMessage;
import com.defangit.openapis.wechat.mp.message.resp.TextResponse;
import com.defangit.openapis.wechat.mp.rest.AbstractWxmpConfig;
import com.laogen.jersey_util.providers.SLF4JLoggingFeature;
import laogen.lang.exception.ParameterNotValidException;
import laogen.util.StringUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhangfagen on 2019/1/14.
 */
public class AwardWxmpConfig extends AbstractWxmpConfig {
    public AwardWxmpConfig(String gh){
        super(gh);
    }

    public ResponseMessage awardByKey(String openId, String key){
        Pattern pattern= Pattern.compile(".*(qz|cj|QZ|CJ)(\\d+)$");
        Matcher matcher=pattern.matcher(key);
        if(matcher.find()){
            int id=Integer.parseInt(matcher.group(2));
            WinningInfo info=null;
            try {
                info=new WinningInfoService().attendAward(id,openId);
            }catch (ParameterNotValidException pne){
                return new TextResponse().setContent(pne.getReadableMessage().getAdvice());
            }
            if(info==null){
                return makeLostInfo();
            }else{
                switch (info.getStatus()) {
                    case WINED:
                        return makePrizeInfo(info);
                    case ATTENDED:
                        return makeAttendedInfo(info);
                }

            }
        }else{
            SLF4JLoggingFeature.JERSEY_LOGGER.info("key值没有匹配规则需求");
        }
        return null;
    }

    protected ResponseMessage makeAttendedInfo(WinningInfo info){
        return new TextResponse()
                .setContent("感谢您，您已成功报名抽奖");
    }

    protected ResponseMessage makeLostInfo(){
        return new TextResponse()
                .setContent("很遗憾，您这次未中奖！");
    }

    protected ResponseMessage makePrizeInfo(WinningInfo info){
        String rst = "恭喜您，您已中奖：" + info.getPrize().getPrizeName();
        if (StringUtil.notEmpty(info.getPrize().getPrizeDetail())) {
            rst += System.lineSeparator() + "=============" +
                    System.lineSeparator() + info.getPrize().getPrizeDetail();
        }
        if (StringUtil.notEmpty(info.getPrize().getAward().getAwardRule())) {
            rst += System.lineSeparator() + "=============" +
                    System.lineSeparator() + info.getPrize().getAward().getAwardRule();
        }
        return new TextResponse().setContent(rst);
    }
}
